#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on 18-1-2
@author: yzw
@desc:
"""
import json
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from blog_yzw.blog_app.models import *
from blog_yzw.blog_app.utils import get_id, md5


# 跳转用户列表
def turn_user_list(request):
	return render(request, 'user/user.html')


# 加载用户数据
@csrf_exempt
def load_user_data(request):
	result_dict = {}
	data_list = []
	obj_list = User.objects.all()
	if 'phone' in request.POST:
		phone = request.POST['phone']
		if phone != '':
			obj_list = obj_list.filter(phone__icontains=phone)

	count = obj_list.count()
	# 限制返回数:分页
	if 'start' and 'limit' in request.POST:
		start = int(request.POST['start'])
		limit = int(request.POST['limit'])
		limit = start + limit
		obj_list = obj_list[start:limit]
	if obj_list.exists():
		for obj in obj_list:
			data_dict = {}
			if obj.status == '1':
				status = '审核通过'
			elif obj.status == '0':
				status = '未审核'
			else:
				status = '未通过'
			data_dict['user_id'] = obj.id
			data_dict['user_name'] = obj.name
			data_dict['status'] = status
			data_dict['phone'] = obj.phone
			if obj.last_login_time is not None:
				data_dict['last_login_time'] = obj.last_login_time.strftime('%Y-%m-%d %H:%M:%S')
			data_list.append(data_dict)
		result_dict['data'] = data_list
		result_dict['code'] = 0
		result_dict['count'] = count
	return HttpResponse(json.dumps(result_dict), content_type="application/json")


# 用户注册
@csrf_exempt
def user_register(request):
	if 'phone' in request.POST and 'password' in request.POST and 'name' in request.POST:
		phone = request.POST['phone']
		user_obj = User.objects.filter(phone=phone)
		if user_obj.exists():
			return HttpResponse('{"msg": "注册失败，号码已存在"}', content_type="application/json")
		password = request.POST['password']
		name = request.POST['name']
		User.objects.create(id=get_id(), phone=phone, password=md5(password), status='0', name=name,
		                    last_login_time=None)
		return HttpResponse('{"msg": "注册成功"}', content_type="application/json")
	return HttpResponse('{"msg": "参数异常"}', content_type="application/json")
